/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.faare.persistence;

import opiam.admin.faare.config.javabeans.JBLdapConfig;
import opiam.admin.faare.service.UserContext;

import netscape.ldap.LDAPRebind;
import netscape.ldap.LDAPRebindAuth;

import org.apache.log4j.Logger;


/**
 * Class used for referral support.<br>
 * OPIAM-Admin creates an instance of this class at each LDAP conenction creation ans parameters the connection as
 * follows :<br>
 * <code>
 *  ldapConnection.setOption(LDAPConnection.REFERRALS_REBIND_PROC, ldapFaareRebind);
 * </code><br>
 * This allows to follow referrals and to bind to the referred server with the same credentials as
 * current connection.
 */
public class LDAPFaareRebind implements LDAPRebind
{
    /** Logger. */
    private static Logger _logger = Logger.getLogger(LDAPFaareRebind.class);

    /** Master connection DName. */
    private String dn;

    /** Master connection Password. */
    private String pwd;

    /** LDAPRebindAuth object. */
    private LDAPRebindAuth myRebindInfo;

    /**
     * Creates a new LDAPFaareRebind object in "user" connection mode.
     * @param userContext User context.
     */
    public LDAPFaareRebind(UserContext userContext)
    {
        dn = userContext.getDn();
        pwd = userContext.getPwd();
        _logger.debug("LDAPFaareRebind UserContext dn : " + dn);
        _logger.debug("LDAPFaareRebind UserContext pwd : " + pwd);
    }

    /**
     * Creates a new LDAPFaareRebind object in "appli" connection mode.
     * @param ldapConfig LDAP server configuration defined in faare_mapping.xml.
     */
    public LDAPFaareRebind(JBLdapConfig ldapConfig)
    {
        dn = ldapConfig.getAppliDN();
        pwd = ldapConfig.getAppliPwd();
        _logger.debug("LDAPFaareRebind JBLdapConfig dn : " + dn);
        _logger.debug("LDAPFaareRebind JBLdapConfig pwd : " + pwd);
    }

    /**
     * This method is called by the LDAP library when it needs to follow a referral to
     * specified directory server.
     *
     * @param host Referred server host name or address.
     * @param port Referred server port number.
     *
     * @return Rebind Object to be used by LDAP library.
     */
    @Override
	public LDAPRebindAuth getRebindAuthentication(String host, int port)
    {
        myRebindInfo = new LDAPRebindAuth(dn, pwd);
        _logger.debug("getRebindAuthentication  dn : " + dn);
        _logger.debug("getRebindAuthentication  pwd : " + pwd);
        _logger.debug("getRebindAuthentication  host : " + host);
        _logger.debug("getRebindAuthentication  port : " + port);

        return myRebindInfo;
    }
}
